/**
 * @description order controller
 * @author liyunfu
 */
const Order = require("../models/Order");
const Product = require("../models/Product");
const Address = require("../models/Address");
/**
 * 创建订单
 * @param {string} username 用户名
 * @param {Object} data 订单数据
 */
async function createOrder(username, data) {
  const {
    addressId,
    shopId,
    shopName,
    isCanceled = false, //默认值false
    products = [], //默认值
  } = data;

  //根据addressId获取地址信息
  const address = await Address.findById(addressId);

  //获取商品列表
  const pIds = products.map((p) => p.id); //['商品1-id','商品2-id']
  const productList = await Product.find({
    shopId,
    _id: { $in: pIds },
  });

  //拼接上购买数量
  const productListWithSales = productList.map((p) => {
    //商品id
    const id = p._id.toString();

    //通过商品 id 可以找到销售数量
    const filterProducts = products.filter((item) => item.id === id);
    if (filterProducts.length === 0) {
      throw new Error("未找到匹配的销售数量");
    }
    return {
      product: p,
      orderSales: filterProducts[0].num,
    };
  });

  //创建订单
  const newOrder = await Order.create({
    username,
    shopId,
    shopName,
    address,
    isCanceled,
    products: productListWithSales,
  });
  return newOrder
}

module.exports = {
  createOrder,
};
